package com.zbs.framework.security.config;

import com.zbs.framework.security.filter.DynamicSecurityFilter;
import com.zbs.framework.security.handler.TokenLogoutHandle;
import com.zbs.framework.security.handler.UnAccessHandler;
import com.zbs.framework.security.handler.UnAuthorizedEntryPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.session.HttpSessionEventPublisher;

/**
 * @author: Zbs
 * @createTime: 2021/2/1 17:09
 */
@AutoConfiguration
@Slf4j
public class SecurityConfig {

    @Autowired
    private UnAuthorizedEntryPoint unAuthorizedEntryPoint;
    @Autowired
    private UnAccessHandler unAccessHandler;
    @Autowired
    private TokenLogoutHandle tokenLogoutHandle;
    @Autowired
    private DynamicSecurityFilter dynamicSecurityService;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .authorizeRequests().antMatchers(FrameworkConstants.IGNORING_URL).permitAll()//不需要认真接口放行
                .and()
                .authorizeRequests().antMatchers(FrameworkConstants.STATIC_IGNORING_URL).permitAll()
                .and()
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .logout().logoutUrl(FrameworkConstants.LOGOUT_URL).addLogoutHandler(tokenLogoutHandle)
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //配置无状态Session 否则会堆积大量Session
                .and().exceptionHandling().authenticationEntryPoint(unAuthorizedEntryPoint).accessDeniedHandler(unAccessHandler)
                .and().addFilterBefore(dynamicSecurityService, FilterSecurityInterceptor.class)
                .csrf().requireCsrfProtectionMatcher(new SecurityRequiresCsrfMatcher()).disable().build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }


}
